﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Bainx.Extend;

namespace Bainx.WPF.Extend.Control
{
    /// <summary>
    /// TabWebBrowser.xaml 的交互逻辑
    /// </summary>
    public partial class TabWebBrowser : UserControl
    {
        private Window owner;

        public Window Owner
        {
            get { return owner; }
            set { owner = value; }
        }

        int LastIndex = -1;

        int CurrentIndex = -1;

        WebBrowserUserControl CurrentWebBrowser;

        private bool AllowChangeSelected = true;


        public TabWebBrowser()
        {
            InitializeComponent();
           
            HeaderTabControl.SelectionChanged += new SelectionChangedEventHandler(HeaderTabControl_SelectionChanged); 
            
            CurrentContent.SizeChanged += new SizeChangedEventHandler(CurrentContent_SizeChanged);
            Loaded += new RoutedEventHandler(TabWebBrowser_Loaded);
        }

        void TabWebBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            SetCurrentWebBrowser(0);
        }

       
        public TabWebBrowser(Window Owner)
            : this()
        {
            owner = Owner;
        }
        void HeaderTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabControl a = sender as TabControl;
            if (a == null) return;

            try
            {
                if (CloseTabItem)
                {
                    CloseTabItem = false;
                    CurrentContent.Children.RemoveAt(HeaderTabControl.SelectedIndex);
                    HeaderTabControl.Items.RemoveAt(HeaderTabControl.SelectedIndex);
                }
                else
                {
                    // Information.MessageToFile("a.log", HeaderTabControl.IsMouseOver);
                    System.Console.WriteLine("HeaderTabControl.IsMouseOver={0}", HeaderTabControl.IsMouseOver);
                    System.Console.WriteLine("HeaderTabControl.SelectIndex={0}, sender.SelectedIndex={1}", HeaderTabControl.SelectedIndex, a.SelectedIndex);
                    System.Console.WriteLine("LastIndex={0},CurrentIndex={1},SelectIndex={2}", LastIndex, CurrentIndex, HeaderTabControl.SelectedIndex);

                    //if (HeaderTabControl.IsMouseOver || AllowChangeSelected)
                    {
                        LastIndex = CurrentIndex;
                        CurrentIndex = HeaderTabControl.SelectedIndex;
                        SetCurrentWebBrowser(CurrentIndex);
                    }

                    System.Console.WriteLine("=====>LastIndex={0},CurrentIndex={1},SelectIndex={2}", LastIndex, CurrentIndex, HeaderTabControl.SelectedIndex);
                    //else
                    //{
                    //    TabControl a = sender as TabControl;
                    //    a.SelectedIndex = LastIndex;
                    //}
                }
            }
            catch (Exception ex)
            {
                ex.MessageToLogFile();
            }


        }     

        void CurrentContent_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if(owner!=null)
            Reposition();
        }
        public void Add(Uri uri)
        {
            Add(uri, "新标签页");
        }
        /// <summary>
        /// 添加一个浏览器
        /// </summary>
        public void Add(Uri uri, string Header)
        {
            //WebBrowserUserControl webborwser = new WebBrowserUserControl(owner);
            Style style = (Style)this.Resources["TabItemStyle1"];
            TabItemWebBrowser tabitem = new TabItemWebBrowser(owner, style, uri, Header);
            tabitem.Content = new WebBrowserCtrlPanel(tabitem.WebBrowser);
            tabitem.NewWindow += new System.ComponentModel.CancelEventHandler(tabitem_NewWindow);

            //TabItem tabitem = new TabItem();
            //tabitem.Header = Header;
            CurrentContent.Children.Add(tabitem.WebBrowser);
            HeaderTabControl.Items.Insert(CurrentContent.Children.Count-1, tabitem); 
        }

        void tabitem_NewWindow(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                System.Windows.Forms.WebBrowser webBrowser_temp = (System.Windows.Forms.WebBrowser)sender;
                string newUrl = webBrowser_temp.Document.ActiveElement.GetAttribute("href");
                Add(new Uri(newUrl));
                e.Cancel = true;
            }
            catch (Exception ex)
            {
                //ex.Show(true);
                ex.MessageToLogFile();
            }
        }

        //void webborwser_NewWindow(object sender, System.ComponentModel.CancelEventArgs e)
        //{
        //    System.Windows.Forms.WebBrowser webBrowser_temp = (System.Windows.Forms.WebBrowser)sender;
        //    string newUrl = webBrowser_temp.Document.ActiveElement.GetAttribute("href");
        //    Add(new Uri(newUrl));
        //    e.Cancel = true;
        //}
        ///// <summary>
        ///// 获取当前浏览器索引，根据元素的Visibility=Visible
        ///// </summary>
        //public int GetCurrentWebBrowserIndex()
        //{
        //    int index=-1;
        //    bool tmp = false;
        //    foreach (UIElement item in CurrentContent.Children)
        //    {
        //        ++index;
        //        if (item.Visibility == System.Windows.Visibility.Visible)
        //        {
        //            tmp = true;
        //            break;
        //        }                
        //    }
        //    return tmp ? index : -1;
        //}
        /// <summary>
        /// 设置当前浏览器
        /// </summary>
        private void SetCurrentWebBrowser(int index)
        {
            try
            {
                if (index >= 0 && index < CurrentContent.Children.Count)
                {
                    CurrentWebBrowser = (WebBrowserUserControl)CurrentContent.Children[index];
                    if (CurrentWebBrowser != null)
                        CurrentWebBrowser.Visibility = Visibility.Visible;

                    for (int i = 0; i < CurrentContent.Children.Count; i++)
                    {
                        if (i != index)
                        {
                            CurrentContent.Children[i].Visibility = System.Windows.Visibility.Hidden;
                        }
                    }
                }
                AllowChangeSelected = false;
            }
            catch (Exception ex)
            {
                AllowChangeSelected = true;
                ex.MessageToLogFile();
            }
        }
        
        /// <summary>
        /// 重新定位浏览器位置
        /// </summary>
        public void Reposition()
        {
            Reposition(owner);
        }
        /// <summary>
        /// 重新定位浏览器位置
        /// </summary>
        public void Reposition(Window Owner)
        {
            owner = Owner;
            if (CurrentWebBrowser != null)
            {
                //System.Console.WriteLine(CurrentWebBrowser.DocumentTitle);
                //CurrentContent.Background = CurrentWebBrowser.FormToBackgroundBrush();
                CurrentWebBrowser.Reposition(Owner, new Point(CurrentContent.ActualWidth, CurrentContent.ActualHeight));
            }
        }
        //public void 

        public void RepositionBegin()
        {
            CurrentContent.Background = CurrentWebBrowser.FormToBackgroundBrush();
        }
        public void RepositionEnd()
        {
            CurrentWebBrowser.RepositionEnd();
        }

        void webborwser_DocumentTitleChanged(object sender, EventArgs e)
        {
            WebBrowserUserControl wbuc = sender as WebBrowserUserControl;
            if (wbuc != null)
            {
                int index = CurrentContent.Children.IndexOf(wbuc);
                if (index > 0 && index < HeaderTabControl.Items.Count)
                {
                    TabItem tabitem = HeaderTabControl.Items[index] as TabItem;
                    if (tabitem != null)
                    {
                        tabitem.Header = wbuc.DocumentTitle.Length>10?wbuc.DocumentTitle.Substring(0,10):wbuc.DocumentTitle;
                    }
                }
            }
        }

        bool CloseTabItem = false;
        private void CloseTabItem_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// 在此处添加事件处理程序实现。
            CloseTabItem = true;
            //Button a = sender as Button;
            //Border b = a.Parent as Border;
            //Grid c = b.Parent as Grid;
            //Border d = c.Parent as Border;
            //Grid f = d.Parent as Grid;
            //var g = f.Parent;
            //Grid g = f.Parent as Grid;
            //b.Parent

        }

    }
}
